﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using Newtonsoft.Json.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace AzureFiddlerCore.Demo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // please note that this Connect method will result in a new container each page load
                // a better approach may be to connect once across the application
                // if you attempt this, please be careful to perform the connect at a point in the lifecycle
                // where the application is fully loaded.

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("AzureFiddlerCore.ConnectionString"));
                var localResource = RoleEnvironment.GetLocalResource("tmpSazLocation");

                var filterList = new List<string>();
                filterList.Add("search.twitter.com");

                AzureFiddlerCoreLib.AzureFiddlerCore.Connect(storageAccount, filterList, localResource);
                System.Diagnostics.Trace.TraceInformation("Connected OK");

            }
            catch (Exception ex)
            {
                WebRole._errorLog.AppendLine(ex.ToString());
                System.Diagnostics.Trace.TraceError("Error in OnStart: " + ex.Message);
                System.Diagnostics.Trace.TraceError(ex.ToString());
            }

            using (var wc = new WebClient())
            {
                wc.Headers.Add(HttpRequestHeader.UserAgent, "AzureFiddlerCore.Demo");
                var _proxy = AzureFiddlerCoreLib.AzureFiddlerCore.GetProxy();

                if (_proxy != null)
                {
                    wc.Proxy = _proxy;
                }

                string result = wc.DownloadString("http://search.twitter.com/search.json?q=Windows+Azure");
                JObject jObj = JObject.Parse(result);

                foreach (var item in jObj["results"])
                {
                    phTwitterResults.Controls.Add(new Image() { ImageUrl = item["profile_image_url"].ToString().Trim('"') });
                    phTwitterResults.Controls.Add(new Label() { Text = item["from_user"].ToString().Trim('"') });
                    phTwitterResults.Controls.Add(new Label() { Text = item["text"].ToString().Trim('"') });
                    phTwitterResults.Controls.Add(new System.Web.UI.HtmlControls.HtmlGenericControl("br"));     
                }

                System.Diagnostics.Trace.TraceInformation("Page Loaded ok");
            }            
        }
    }
}
